package com.mjduan.myBank.user.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mjduan.myBank.record.service.IRecordService;
import com.mjduan.myBank.user.service.IUserService;
import com.mjduan.myBank.util.crypto.CryptographyUtil;
import com.mjduan.myBank.util.dateUtil.DateUtil;
import com.mjduan.myBank.util.email.util.MailUtil;
import com.mjduan.myBank.util.entity.Record;
import com.mjduan.myBank.util.entity.User;
import com.mjduan.myBank.util.logger.MyLogger;
import com.mjduan.myBank.util.property.MyProperty;


/**
 * user的controller
 * 
 * @author Duan
 *
 */
@Controller
@RequestMapping("/user/UserController")
public class UserController {
	
	@Autowired
	@Qualifier("UserServiceImpl")
	private IUserService iUserService;
	
	@Autowired
	@Qualifier("RecordServiceImpl")
	private IRecordService iRecordService;
	
	@Autowired
	@Qualifier("MailUtil")
	private MailUtil mailUtil;
	
	/**
	 * 处理用户的登录
	 * 
	 * @param user  封装了用户登录时输入的账号和密码
	 * @param mav 封装了请求结果的数据
	 * @return  ,method=RequestMethod.POST
	 */
	@RequestMapping(value="login")
	@ResponseBody
	public Map<String,Object> login(@ModelAttribute User user,
			HttpServletRequest request){
		Map<String,Object> map = new HashMap<String, Object>();
		
		Validator validator=new Validator();
		List<ConstraintViolation> errors = validator.validate(user);
		if(errors.size()>0){
			map.put(MyProperty.FAIL, MyProperty.FAIL);
			map.put(MyProperty.FAIL_MESSAGE, "用户名和密码不能为空");
			return map;
		}
		
		String password = user.getPassword();
		user.setPassword(CryptographyUtil.md5(password));
		
		map = iUserService.login(user);
		
		if(map.get(MyProperty.STATUS).equals(MyProperty.SUCCESS)){
			User resultUser = (User) map.get("user");
			setHttpSession(request,resultUser);
			addRecord(resultUser.getId(), request);
		}
		
		return map;
	}

	@RequestMapping(value="main")
	public ModelAndView main(ModelAndView mav){
		//OutUtil.println("到success");
		
		mav.setViewName("/pages/main.html");
	    return mav;
	}
	
	/**
	 * 将用户信息存储在HttpSession中
	 * 
	 * @param request
	 * @param user
	 * @return
	 */
	private boolean setHttpSession(HttpServletRequest request,User user){
		HttpSession session=request.getSession(true);
		session.setAttribute(MyProperty.MY_SESSION, user);
		
		return true;
	}
	
	/**
	 * 记录用户的登录记录
	 * 
	 * @param user
	 * @param request
	 * @return
	 */
	private boolean addRecord(long userId,HttpServletRequest request){
		Record record=new Record();
		User user = new User();
		user.setId(userId);
		
		//若是localhost的方式访问则得到的是ipv6，若是127.0.0.1访问则是ipv4
		String host=request.getRemoteHost();

		if(host.contains(".")){
			record.setIpv4(host);   
		}else{
			record.setIpv6(host);
		}
		
		record.setUser(user);
		record.setTime(DateUtil.getCurrentDateStr());

		return this.iRecordService.addRecord(record);
	}
	
	/**
	 * 从HttpServletRequest中获取User信息
	 * 
	 * @return
	 */
	@RequestMapping(value="getUserInfo")
	@ResponseBody
	public Map<String,Object> getUserInfo(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String, Object>();
		
		User user = (User) request.getSession().getAttribute(MyProperty.MY_SESSION);
		if(user!=null){
			map.put(MyProperty.STATUS, MyProperty.SUCCESS);
			map.put("name", user.getName());
		}else{
			String fail_message="操作失败!请重新登录而后重试看看!";
			map.put(MyProperty.STATUS, MyProperty.FAIL);
			map.put(MyProperty.FAIL_MESSAGE, fail_message);
		}
		
		return map;
	}
	
	@RequestMapping(value="registeUser")
	@ResponseBody
	public Map<String,Object> registeUser(@ModelAttribute User user) throws UnsupportedEncodingException{
		//MyLogger.info("收到的user:"+user.toString());
		
		Map<String,Object> map;
		user.setPassword(CryptographyUtil.md5(user.getPassword()));
	    String name = new String(user.getName().getBytes("iso-8859-1"),"utf-8");
		user.setName(name);
	    
		user.setTime(DateUtil.getCurrentDateStr());
		
		map = iUserService.registeUser(user);
		if(!map.get(MyProperty.STATUS).equals(MyProperty.FAIL)){
			sendEmail((User)map.get("user"));
		}
		/*用户信息不能返回客户端*/
		map.remove("user");
		
		return map;
	}
	
	private void sendEmail(User user){
		MyLogger.info("收到的info:"+user.toString());
		String url= "http://localhost:8080/myBank10/email/EmailController/emailConfirm";
	    url = url + "?id="+user.getId()+"&password="+user.getPassword();
		String subject = "myBank验证邮件";
		String content = "<html><body><a href=\""+url+"\">点击邮件激活账户!</a></body></html>";
		
		this.mailUtil.send(user.getEmail(), subject, content);
		
	}
}
